package io.shallwe.stovingoven;

import HslCommunication.Profinet.Siemens.SiemensPLCS;
import HslCommunication.Profinet.Siemens.SiemensS7Net;
import com.jfinal.kit.*;
import io.shallwe.common.model.Account;
import io.shallwe.common.model.LineInfo;
import io.shallwe.common.model.StovingOven;

import java.util.Date;
import java.util.List;

/**
 * 烘干炉温度控制
 * 连续多个电泳框为空，第一个电泳框出烘干炉开始降温
 * 连续多个空箱第一个有料电泳框进入后开始升温
 * @author 王小伟
 * @date 2019-07-10 11:09:01
 **/
public class StovingOvenTemperatureService {
    private StovingOven dao=StovingOven.dao;

    private  LineInfo lineInfoDao = new LineInfo().dao();
    private SiemensS7Net plc=null;

    public StovingOvenTemperatureService(){
        PropKit.use("").appendIfExists("");
        if(PropKit.getBoolean("StovingOvenTemperatureEnable",false)) {
            plc = new SiemensS7Net(SiemensPLCS.S1500, PropKit.get("PLC","172.30.31.1"));
            plc.ConnectServer();
            plc.SetPersistentConnection();
        }
    }

    public StovingOven getStovingOven(){
        StovingOven stovingOven = dao.findFirst("select top 1 * from t_stove_oven_temperature ");
        if(stovingOven==null){
            stovingOven =new StovingOven()
                    .setConfigStatus(0)
                    .setDownTag("")
                    .setUpdateTime(new Date())
                    .setMaxCount(10)
                    .setRiseTag("")
                    .setChangeBy("1");
            stovingOven.save();
        }
        return stovingOven;
    }


    public Ret saveStovingOven(StovingOven stovingOven, Account loginAccount ){
        stovingOven.setUpdateTime(new Date()).setChangeBy(loginAccount.getId());
        if(stovingOven.update()) {
            return Ret.ok("msg", "修改成功").set("stovingOven", stovingOven);
        }else{
            return Ret.fail("msg", "修改失败");
        }
    }

    public List<LineInfo> findContinueBlankRise(Integer start , Integer end){
        Kv condition= Kv.by("start",start).set("end",end);
        return  lineInfoDao.template("lineInfo.findContinueBlankRise",condition).find();
    }

    public List<LineInfo> findContinueBlankDown(Integer start ,Integer end){
        Kv condition= Kv.by("start",start).set("end",end);
        return lineInfoDao.template("lineInfo.findContinueBlankDown",condition).find();
    }

    /**
     * 检查连续10个空框出烘干区（烤炉）第一个有料框进来要升温
     */
    public void checkAndRiseTemperature(){
        StovingOven stovingOven = getStovingOven();
        if(stovingOven==null){
            return;
        }
        Integer start = 86;
        Integer end =start+2+stovingOven.getMaxCount();
        List<LineInfo> continueBlank = findContinueBlankRise(start, end);
        if(continueBlank.size()>0){
            if(StrKit.isBlank(continueBlank.get(continueBlank.size()-1).getTraceNo())){
                long count = continueBlank.stream().filter(lineRack -> StrKit.isBlank(lineRack.getTraceNo())).count();
                if(count >= stovingOven.getMaxCount()){
                    if(plc!=null){
                        try {
                            plc.Write(stovingOven.getRiseTag(),true);
                            Thread.sleep(1000);
                            plc.Write(stovingOven.getRiseTag(),false);
                        }catch (Exception e){
                            LogKit.error(e.getMessage());
                            LogKit.error(e.toString());
                        }
                    }
                }
            }
        }

    }

    /**
     * 检查连续10个空框出烘干区（烤炉）第一个空框出来要降温
     */
    public void  checkAndCalmDown() {
        StovingOven stovingOven = getStovingOven();
        if(stovingOven==null){
            return;
        }
        Integer start = 141;
        Integer end =start+2+stovingOven.getMaxCount();
        List<LineInfo> continueBlank = findContinueBlankDown(start, end);
        if(continueBlank.size()>0){
            if(StrKit.isBlank(continueBlank.get(0).getTraceNo())){
                long count = continueBlank.stream().filter(lineRack -> StrKit.isBlank(lineRack.getTraceNo())).count();
                if(count >= stovingOven.getMaxCount()){
                    if(plc!=null){
                        try {
                            plc.Write(stovingOven.getDownTag(),true);
                            Thread.sleep(1000);
                            plc.Write(stovingOven.getDownTag(),false);
                        }catch (Exception e){
                            LogKit.error(e.getMessage());
                            LogKit.error(e.toString());
                        }
                    }
                }
            }
        }
    }
}
